﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.Mvc;
using Xyz.Web.Reservation.Areas.Auth.Models;
using Xyz.Web.Reservation.Models;
using Xyz.Web.Reservation.Repositories;

namespace Xyz.Web.Reservation.Areas.Auth.Controllers
{
    public class AuthController : Controller
    {
        public ActionResult Login()
        {
            return View(new AuthModel());
        }

        [HttpPost]
        public ActionResult Login(AuthModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var customer = AuthRepository.Login(model.UserName, model.Password);

                if (customer!=null)
                {
                    Session["Customer"] = customer.ToModel();
                    FormsAuthentication.SetAuthCookie(model.UserName, false);

                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }

                    return RedirectToAction("Search", "Flight", new {area = ""});
                }
            }

            ModelState.AddModelError("", "Invalid User Name or Password.");

            return View(model);
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            Session.Abandon();

            return RedirectToAction("Search", "Flight", new { area = "" });
        }
    }
}
